package org.jash.comment.utils

import android.annotation.SuppressLint
import android.util.Log
import androidx.arch.core.internal.SafeIterableMap
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.Arrays

class SingleListData<T>: MutableLiveData<T>() {
    @SuppressLint("RestrictedApi")
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
//        super.observe(owner, observer)
        val version = LiveData::class.java.getDeclaredField("mVersion")
            .apply { isAccessible = true }
            .get(this) as Int // 获取当的版本号
        val map = LiveData::class.java.getDeclaredField("mObservers")
            .apply { isAccessible = true }
            .get(this) as SafeIterableMap<Observer<in T>, Any?> // 获取订阅集合

        val o = Class.forName("androidx.lifecycle.LiveData\$LifecycleBoundObserver")
            .getDeclaredConstructor(LiveData::class.java, LifecycleOwner::class.java, Observer::class.java)
            .apply { isAccessible = true }
            .newInstance(this, owner, observer) as LifecycleEventObserver // 创建ObserverWrapper 对象

        val field = Class.forName("androidx.lifecycle.LiveData\$ObserverWrapper")
            .getDeclaredField("mLastVersion")
            .apply { isAccessible = true }
        field.set(o, version) // 设置最后的版本号
        map.putIfAbsent(observer, o)
        owner.lifecycle.addObserver(o)
    }
}